from django.shortcuts import render

# Create your views here.

from . import models
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
# GenericViewSet:自动生成路由，配置两条（queryset，serialzer）
# ListModelMixin：list
from . import serializer
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response


class BannerView(GenericViewSet, ListModelMixin):
    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders')[:settings.BANNER_SIZE]
    serializer_class = serializer.BannerModelSerializer

    # 改成，先从缓存中取，缓存中如果有，直接返回，没有，再去数据库查

    def list(self, request, *args, **kwargs):
        # 如果缓存中有值，直接取出来返回，速度很快
        banner_data = cache.get('banner_data')
        if banner_data:

            print('走了缓存')
            return Response(data=banner_data)

        # 如果缓存中没有，再走数据，查出来，放到缓存中
        res = super().list(request, *args, **kwargs)
        # 把首页轮播图数据放到缓存中
        cache.set('banner_data', res.data)
        print('没走缓存')
        return res
